package com.tc.excel;

import com.tc.excel.handler.ExcelArgumentResolvers;
import com.tc.excel.handler.ExcelReturnValueHandler;
import org.springframework.beans.factory.SmartInitializingSingleton;
import org.springframework.beans.factory.config.SmartInstantiationAwareBeanPostProcessor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.HandlerMethodReturnValueHandler;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;

/**
 * @Auther: tianchao
 * @Date: 2025/2/14 15:50
 * @Description:
 */
@Configuration
public class ExcelConfiguration{
    private RequestMappingHandlerAdapter requestMappingHandlerAdapter;

    public ExcelConfiguration(RequestMappingHandlerAdapter requestMappingHandlerAdapter) {
        this.requestMappingHandlerAdapter = requestMappingHandlerAdapter;
    }
    @PostConstruct
    public void setReturnValueHandlers() {
        List<HandlerMethodReturnValueHandler> returnValueHandlers = requestMappingHandlerAdapter.getReturnValueHandlers();
        List<HandlerMethodReturnValueHandler> newHandlers = new ArrayList<>();
        newHandlers.add(excelReturnValueHandler());
        if (returnValueHandlers != null){
            newHandlers.addAll(returnValueHandlers);
        }
        requestMappingHandlerAdapter.setReturnValueHandlers(newHandlers);
    }
    @PostConstruct
    public void setArgumentResolvers() {
        List<HandlerMethodArgumentResolver> argumentResolvers = requestMappingHandlerAdapter.getArgumentResolvers();
        List<HandlerMethodArgumentResolver> newResolvers =  new ArrayList<>();
        newResolvers.add(excelArgumentResolvers());
        if (argumentResolvers != null){
            newResolvers.addAll(argumentResolvers);
        }
        requestMappingHandlerAdapter.setArgumentResolvers(newResolvers);
    }


    @Bean
    public ExcelArgumentResolvers excelArgumentResolvers() {
        return new ExcelArgumentResolvers();
    }
    @Bean
    public ExcelReturnValueHandler excelReturnValueHandler(){
        return new ExcelReturnValueHandler();
    }

}
